#!/bin/bash
source $DRAW_INI
source $DRAW_CFG

mkdir -p ../csv

DFILE="../csv/$1.recal_data.csv"

rm core.* 2> /dev/null

# Check for missing index
if [ -s $1.bam ]
then
 #check for index
 if [ ! -s $1.bai ];then samtools index $1.bam $1.bai;fi
else
 echo "missing input BAM: " $1.bam
 exit 100
fi

# Check BAM EOF
BAM_28=$(tail -c 28 $1.bam|xxd -p)
if [ "$MAGIC28" != "$BAM_28" ] 
then
  echo "Error with BAM EOF" 
  exit 100
fi

if [ -z $SNPDB ];then
  DTAG="--run_without_dbsnp_potentially_ruining_quality"
else
  DTAG="-knownSites $SNPDB"
fi

if [ $TARGET_FLANKS_FILE == "WGS" ];then
  LTAG=""
else
  LTAG="-L $TARGET_FLANKS_FILE"
fi

java -Xmx3072m -jar $GATK \
  -l INFO \
  -R $REF_FASTA \
  $DTAG \
  $LTAG \
  -I $1.bam \
  -T BaseRecalibrator \
   -cov ReadGroupCovariate \
   -cov QualityScoreCovariate \
   -cov CycleCovariate \
   -cov ContextCovariate \
   -o "$DFILE"

EXITSTATUS=$?

#force error when missing recalFile. Would prevent continutation of pipeline
if [ ! -s "$DFILE" ]
then
 echo "Missing DFILE in ../csv" 
 exit 100
fi

# Check for core dumps (errors) from bwa
CORE_LIST=$(ls core.*)
if [ -n "$CORE_LIST" ]
  then
   echo "Found core dumps. Exiting with error." 
   exit 100
fi

exit $EXITSTATUS
